package com.rotten;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream.GetField;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Client {
        
        private static String API_Key = "ecn3as7yquxyyz6gzkennhmf";
        private static String ID_movie = "770672122"; //toy story 3
        public static Hashtable<Integer, Movie> results = new Hashtable<Integer, Movie>(); //save search results
        private String critics = "";
        private String country = "PT";
        static int page_limit = 5;
        
        Client(){}
        
        //search links;

        //String link_search = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=" + API_Key+ "&q=";
                
        String link_critics = "http://api.rottentomatoes.com/api/public/v1.0/movies/ " + ID_movie + "/reviews.json?apikey=+" + API_Key;
        
        String link_opening = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/opening.json?apikey=" + API_Key;

        public String showOpenings(){                
        		String res ="";
                String searchMsg = link_opening;// + "&country=" + country;
                
                return send_command(searchMsg);
        }
        
        //efectua uma pesqusisa e recebe apenas alguma informacao de varios filmes
        public String Search_Movies(String search, int page){             
                
                String searchTerm = "";
                searchTerm = search;
                searchTerm = searchTerm.replace(' ', '+');                
                
                String searchMsg = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="+ API_Key +"&q="+ 
                					searchTerm +"&page_limit=" + page_limit + "&page=" + page;
                                
                return send_command(searchMsg);
        }
        
        public String get_Movie(int movie){        	
        	ID_movie = Integer.toString(movie);
        	String link_movie = "http://api.rottentomatoes.com/api/public/v1.0/movies/" + ID_movie + ".json?apikey=" + API_Key;
        	return send_command(link_movie);
        }
        
        public static String send_command(String link){
                        
                String result = "";

                // Send a GET request to the servlet
                try {
                        // Construct data
                        StringBuffer data = new StringBuffer();

                        URL url = new URL(link);
                        URLConnection conn = url.openConnection();
                        // Get the response
                        BufferedReader rd = new BufferedReader(new InputStreamReader(
                                        conn.getInputStream()));
                        String line;
                        while ((line = rd.readLine()) != null) {
                                result += line +'\n';
                                //System.out.println(line);
                        }
                        rd.close();
                } catch (Exception e) {
                        e.printStackTrace();
                }                        
                return result.trim();
        }
        
        
        public Hashtable<Integer, Movie> parse_searchResults(String resultados){
        	
        	results.clear();  //apaga os resultados anteriores
        	
        	JSONObject j;
			try {
				System.out.println(resultados +'\n');
				j = new JSONObject(resultados);
				System.out.println("Resultados encontrados: " + j.get("total"));
				JSONArray array = j.getJSONArray("movies");
				
				//Faz o parser dos varios filmes
				for(int i =0;i<array.length();++i){
					String m = array.get(i).toString();
					System.out.println(m);
					JSONObject movie = new JSONObject(m);						
					
					int id = (int)movie.getInt("id");
					
					String title = (String)movie.get("title");
					
					int year = (int) movie.getInt("year");
					String synopsis ="";
					try{
						synopsis =(String) movie.get("synopsis");
					}
					catch(Exception E){}
					int runtime = 0;
					try{
					runtime = (int) movie.getInt("runtime");
					}
					catch(Exception E){}
					
					JSONObject posters = (JSONObject) movie.get("posters");
					String thumbnail = (String)posters.get("thumbnail");
					String profile = (String)posters.get("profile");
					
					JSONObject ratings = (JSONObject) movie.get("ratings");
					int critics_score = ratings.getInt("critics_score");
					int audience_score = ratings.getInt("audience_score");		
				
					Movie mov = new Movie();
					mov.setId(id);
					mov.setYear(year);
					mov.setTitle(title);
					mov.setCritics_score(critics_score);
					mov.setAudience_score(audience_score);
					mov.setPoster_thumbnail(thumbnail);
					mov.setPoster_profile(profile);
					System.out.println();
					
					results.put(id, mov);    //adiciona o filme aos resultados
				}				
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return results;
        }
        
	public Movie parse_movieResults(String resultados) {
		Movie mov = new Movie();
		try {
			JSONObject movie = new JSONObject(resultados);
			int id = (int) movie.getInt("id");
			String title = (String) movie.get("title");
			int year = (int) movie.getInt("year");
			String synopsis = "";
			try{
				synopsis =(String) movie.get("synopsis");
			}
			catch(Exception E){}
			int runtime = 0;
			try{
			runtime = (int) movie.getInt("runtime");
			}
			catch(Exception E){}
			
			JSONObject posters = (JSONObject) movie.get("posters");
			String thumbnail = (String) posters.get("thumbnail");
			String profile = (String) posters.get("profile");
			String detailed = (String) posters.get("detailed");
			JSONObject ratings = (JSONObject) movie.get("ratings");
			int critics_score = ratings.getInt("critics_score");
			int audience_score = ratings.getInt("audience_score");
			
			Vector<String> g = new Vector<String>();			
			JSONArray genres = (JSONArray) movie.get("genres");
			for(int i=0;i<genres.length();++i)			
				g.add((String) genres.get(i));
			
			String theater = "Not Available";
			String dvd = "Not Available";
			try{
			JSONObject release_dates = (JSONObject) movie.get("release_dates");
			theater = (String) release_dates.get("theater");
			dvd = (String) release_dates.get("dvd");
			}
			catch(Exception E){}
			mov.setId(id);
			mov.setYear(year);
			mov.setTitle(title);
			mov.setSynopsis(synopsis);
			mov.setRuntime(runtime);
			mov.setCritics_score(critics_score);
			mov.setAudience_score(audience_score);
			mov.setPoster_thumbnail(thumbnail);
			mov.setPoster_profile(profile);
			mov.setPoster_detailed(detailed);
			mov.setTheater_date(theater);
			mov.setDVD_date(dvd);
			mov.setGenres(g);
			

		} catch (Exception e) {
		}
		return mov;
	}
	
	public Vector<Movie> parse_openigResults(String resultados){
    	
    	Vector<Movie> results = new Vector<Movie>();
    	
    	JSONObject j;
		try {
			j = new JSONObject(resultados);
			JSONArray array = j.getJSONArray("movies");
			
			//Faz o parser dos varios filmes
			for(int i =0;i<array.length();++i){
				String m = array.get(i).toString();
				JSONObject movie = new JSONObject(m);			
				
				int id = (int)movie.getInt("id");				
				String title = (String)movie.get("title");	
				int year = (int) movie.getInt("year");				
				//String synopsis = (String)movie.get("synopsis");				
				int runtime=0;
				try{
					runtime = (int) movie.getInt("runtime");
				}
				catch(Exception E){}
				
				JSONObject posters = (JSONObject) movie.get("posters");
				String thumbnail = (String)posters.get("thumbnail");
				String profile = (String)posters.get("profile");
				
				JSONObject ratings = (JSONObject) movie.get("ratings");
				int critics_score = ratings.getInt("critics_score");
				int audience_score = ratings.getInt("audience_score");		
			
				Movie mov = new Movie();
				mov.setId(id);
				mov.setYear(year);
				mov.setTitle(title);
				mov.setCritics_score(critics_score);
				mov.setAudience_score(audience_score);
				mov.setPoster_thumbnail(thumbnail);
				mov.setPoster_profile(profile);				
				results.add(mov);    //adiciona o filme aos resultados
			}			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return results;
    }
   
	
	public int getTotalMovie(String json){		
		int total =0;
		JSONObject j;
		try {
			j = new JSONObject(json);
			total = j.getInt("total");
		}
		catch(Exception E){}
		
		return total;
	}
	

        public static void main(String[] args) {        
                Client c = new Client();
                //testes
                String resultados = c.showOpenings();
                Vector<Movie> m = c.parse_openigResults(resultados);
                System.out.println(resultados);
                for(int i=0;i<m.size();++i)
                	System.out.println(m.get(i).getTitle());
               
                resultados = c.get_Movie(771239390);  
                System.out.println(resultados);
                Movie mov = c.parse_movieResults(resultados);
                System.out.println(mov.getPoster_profile());
                System.out.println(mov.getPoster_detailed());
                System.out.println(mov.getPoster_thumbnail());
        }
}
